﻿using System.Text;
using System;
using System.IO;
using System.Windows.Forms;

namespace LogHelper
{
	/// <summary>
	/// Description of logHelper.
	/// </summary>
	public class Log
	{
		public Log()
		{
		}
        public static string FileLogPath="";
		public static void logTransaction(string strLog){
            if(FileLogPath.Equals("")){
                throw new Exception("File log is not set. Please set path for log file.");
            }
			log(strLog);
		}
		
		public static void logTransaction(string strLog,string strFomatOutPut){
			log(strLog);
		}
		public static void logTransaction(Exception e){
			log(e.Message+"\n"+e.StackTrace);
		}
		private static void log(string strLog){
			//string _strDateTime="";
			string strFileRename ="";
			//Grant datetime to log string
			 DateTime datetime  = DateTime.Now;
			 //strLog =String.Format("{0} \n {1}",datetime.ToString("dd:MM:yyyy hh:mm:ss"),strLog);
			 StreamWriter sw = null;
             strLog = System.DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + ": " + strLog;
			//Rename file if file size lager 100Mb
             FileInfo fInfo = new FileInfo(FileLogPath);
			if(fInfo.Exists){
				long sizeFile=	fInfo.Length;
				//rename
				if(Decimal.Divide(sizeFile, 1048576)>100){
					strFileRename= "error_"+datetime.ToString("dd_MM_yyyy hh_mm_ss")+".log";
					try{
                        File.Move(FileLogPath, strFileRename);
					}
					catch{
						throw new Exception("The program is not full access in install directory or an progress is using file error.log.");
					}
				}
			}
			//begin log
			try{

                if (File.Exists(FileLogPath))
                {//Check exist log file
                    sw = File.AppendText(FileLogPath);
					sw.WriteLine(strLog);
				}
				else{//create file log
                    sw = File.CreateText(FileLogPath);
					sw.WriteLine(strLog);
				}
			}catch(Exception e){
				throw new Exception("Can not log error!\n"+e.Message);
			}
			finally{
				if(sw!=null){
					sw.Close();
				}
			}
		}
		
		 public static decimal GetFileSize(long Bytes)
        {
            if (Bytes >= 1073741824)
            {
                Decimal size = Decimal.Divide(Bytes, 1073741824);//GB
                return  size;//gb
            }
            else if (Bytes >= 1048576)
            {
                Decimal size = Decimal.Divide(Bytes, 1048576);
                return  size;//mb
            }
            else if (Bytes >= 1024)
            {
                Decimal size = Decimal.Divide(Bytes, 1024);
                return  size;//kb
            }
            else if (Bytes > 0 & Bytes < 1024)
            {
                Decimal size = Bytes;
                return size;//b
            }
            else
            {
                return 0;
            }

            
        }
	}
}

